package com.vm.db;

import java.util.ArrayList;
import java.util.List;

import com.vm.model.RememberPsd;

import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.util.Log;

public class RememberPsdDao {
	private static final String TAG = "RememberPsdDao";

	public RememberPsdDao(Context context) {
		if (DBOpenHelper.db == null) {
			new DBOpenHelper(context);
		}
	}

	public synchronized void insert(RememberPsd rememberPsd) {
		Log.d(TAG, "insert");
		try {
			DBOpenHelper.db
					.execSQL(
							"INSERT INTO rememberPsd(userId,username,psd)VALUES(?,?,?)",
							new Object[] { rememberPsd.getUserId(),
									rememberPsd.getUsername(),
									rememberPsd.getPsd() });
		} catch (SQLException e) {
			Log.d(TAG, "insert---" + e.getMessage());
		}
	}

	public synchronized void update(RememberPsd rememberPsd) {
		Log.d(TAG, "update");
		try {
			DBOpenHelper.db.execSQL(
					"UPDATE rememberPsd SET username=?,psd=? WHERE userId=?",
					new Object[] { rememberPsd.getUsername(),
							rememberPsd.getPsd(), rememberPsd.getUserId() });

		} catch (SQLException e) {
			Log.d(TAG, "update---" + e.getMessage());
		}
	}

	public synchronized RememberPsd query() {
		Log.d(TAG, "query");
		Cursor c = null;
		RememberPsd rememberPsd = null;
		try {
			c = DBOpenHelper.db.rawQuery(
					"SELECT userId,username,psd FROM rememberPsd",
					new String[] {});
			rememberPsd = null;
			if (c.moveToNext()) {
				rememberPsd = new RememberPsd();
				rememberPsd.setUserId(c.getString(0));
				rememberPsd.setUsername(c.getString(1));
				rememberPsd.setPsd(c.getString(2));
			}
		} catch (Exception e) {
			// TODO: handle exception
		} finally {
			if (c != null) {
				c.close();
			}
		}
		return rememberPsd;
	}

	public boolean ifExits(String userId) {
		Log.d(TAG, "ifExists");
		Cursor c = null;
		try {
			c = DBOpenHelper.db.rawQuery(
					"SELECT * FROM rememberPsd WHERE userId=?",
					new String[] { userId });
			if (c.moveToNext()) {
				return true;
			}
		} catch (Exception e) {
			// TODO: handle exception
			Log.d(TAG, "ifExists---" + e.getMessage());
		} finally {
			if (c != null) {
				c.close();
			}
		}
		return false;

	}
	public synchronized List<RememberPsd> selectall() {
		Log.d(TAG, "selectall");
		List<RememberPsd> list=new ArrayList<RememberPsd>();
		Cursor c = null;
		try {
			c=DBOpenHelper.db.rawQuery("SELECT * FROM rememberPsd", null);
			while (c.moveToNext()) {
				RememberPsd rememberPsd = new RememberPsd();
				rememberPsd=new RememberPsd();
				rememberPsd.setUserId(c.getString(0));
				rememberPsd.setUsername(c.getString(1));
				rememberPsd.setPsd(c.getString(2));
				list.add(rememberPsd);
			}
		}catch (SQLException e) {
			Log.d(TAG, "selectall---" + e.getMessage());
		} finally {
			if (c != null) {
				c.close();
			}
		}
		return list;
	}
}